 /**
 * 性能监控工具
 * 提供性能测量、优化建议和资源监控功能
 */

import { createLogger } from './logger';

const perfLogger = createLogger('Performance');
const isDev = import.meta.env.MODE === 'development';

// 性能指标收集器
class PerformanceMonitor {
  constructor() {
    this.metrics = new Map();
    this.timers = new Map();
    this.watchers = new Set();
    this.componentRenderTimes = new Map();
  }

  /**
   * 开始性能计时
   * @param {string} name 计时器名称
   */
  startTimer(name) {
    if (isDev) {
      this.timers.set(name, performance.now());
    }
  }

  /**
   * 结束性能计时并记录
   * @param {string} name 计时器名称
   * @returns {number} 耗时（毫秒）
   */
  endTimer(name) {
    if (!isDev) return 0;
    
    const startTime = this.timers.get(name);
    if (startTime === undefined) {
      perfLogger.warn(`计时器 "${name}" 未找到`);
      return 0;
    }
    
    const duration = performance.now() - startTime;
    this.timers.delete(name);
    
    // 记录指标
    this.recordMetric(name, duration);
    
    // 如果耗时过长，发出警告
    if (duration > 100) {
      perfLogger.warn(`性能警告: ${name} 耗时 ${duration.toFixed(2)}ms`);
    } else {
      perfLogger.debug(`性能指标: ${name} 耗时 ${duration.toFixed(2)}ms`);
    }
    
    return duration;
  }

  /**
   * 记录性能指标
   * @param {string} name 指标名称
   * @param {number} value 指标值
   */
  recordMetric(name, value) {
    if (!this.metrics.has(name)) {
      this.metrics.set(name, []);
    }
    
    const values = this.metrics.get(name);
    values.push({
      value,
      timestamp: Date.now()
    });
    
    // 只保留最近100个记录
    if (values.length > 100) {
      values.shift();
    }
  }

  /**
   * 获取性能统计
   * @param {string} name 指标名称
   * @returns {Object} 统计信息
   */
  getStats(name) {
    const values = this.metrics.get(name);
    if (!values || values.length === 0) {
      return null;
    }
    
    const nums = values.map(v => v.value);
    const sum = nums.reduce((a, b) => a + b, 0);
    const avg = sum / nums.length;
    const min = Math.min(...nums);
    const max = Math.max(...nums);
    
    return {
      count: nums.length,
      avg: parseFloat(avg.toFixed(2)),
      min: parseFloat(min.toFixed(2)),
      max: parseFloat(max.toFixed(2)),
      total: parseFloat(sum.toFixed(2))
    };
  }

  /**
   * 监控组件渲染性能
   * @param {string} componentName 组件名称
   */
  trackComponentRender(componentName) {
    if (!isDev) return () => {};
    
    const startTime = performance.now();
    
    return () => {
      const duration = performance.now() - startTime;
      this.recordMetric(`component-render-${componentName}`, duration);
      
      if (duration > 50) {
        perfLogger.warn(`组件渲染较慢: ${componentName} 耗时 ${duration.toFixed(2)}ms`);
      }
    };
  }

  /**
   * 简化的渲染监控方法（别名）
   * @param {string} componentName 组件名称
   */
  trackRender(componentName) {
    return this.trackComponentRender(componentName);
  }

  /**
   * 监控深度监听器性能
   * @param {string} watcherName 监听器名称
   */
  trackWatcher(watcherName) {
    if (!isDev) return () => {};
    
    const startTime = performance.now();
    
    return () => {
      const duration = performance.now() - startTime;
      this.recordMetric(`watcher-${watcherName}`, duration);
      
      if (duration > 10) {
        perfLogger.warn(`监听器执行较慢: ${watcherName} 耗时 ${duration.toFixed(2)}ms`);
      }
    };
  }

  /**
   * 生成性能报告
   */
  generateReport() {
    if (!isDev) return;
    
    perfLogger.info('=== 性能报告 ===');
    
    for (const [name, _] of this.metrics) {
      const stats = this.getStats(name);
      if (stats) {
        perfLogger.info(`${name}:`, stats);
      }
    }
    
    // 内存使用情况
    if (performance.memory) {
      const memory = performance.memory;
      perfLogger.info('内存使用:', {
        used: `${(memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}MB`,
        total: `${(memory.totalJSHeapSize / 1024 / 1024).toFixed(2)}MB`,
        limit: `${(memory.jsHeapSizeLimit / 1024 / 1024).toFixed(2)}MB`
      });
    }
  }

  /**
   * 清理性能数据
   */
  clear() {
    this.metrics.clear();
    this.timers.clear();
    this.componentRenderTimes.clear();
  }
}

// 创建全局性能监控实例
export const perfMonitor = new PerformanceMonitor();

/**
 * 防抖优化建议检查器
 */
export class DebounceOptimizer {
  constructor() {
    this.functionCalls = new Map();
  }

  /**
   * 检查函数调用频率
   * @param {string} functionName 函数名称
   * @param {number} threshold 阈值（毫秒）
   */
  checkCallFrequency(functionName, threshold = 100) {
    if (!isDev) return;
    
    const now = Date.now();
    const lastCall = this.functionCalls.get(functionName);
    
    if (lastCall && (now - lastCall) < threshold) {
      perfLogger.warn(`函数调用频率过高: ${functionName}，建议添加防抖`);
    }
    
    this.functionCalls.set(functionName, now);
  }
}

export const debounceOptimizer = new DebounceOptimizer();

/**
 * 组合式函数：性能监控Hook
 * @param {string} componentName 组件名称
 */
export function usePerformanceMonitor(componentName) {
  if (!isDev) {
    return {
      startTimer: () => {},
      endTimer: () => 0,
      trackRender: () => () => {},
      trackWatcher: () => () => {},
      getStats: () => null,
      recordMetric: () => {}
    };
  }
  
  return {
    startTimer: (name) => perfMonitor.startTimer(`${componentName}-${name}`),
    endTimer: (name) => perfMonitor.endTimer(`${componentName}-${name}`),
    trackRender: () => perfMonitor.trackRender(componentName),
    trackWatcher: (name) => perfMonitor.trackWatcher(`${componentName}-${name}`),
    getStats: (name) => perfMonitor.getStats(`${componentName}-${name}`),
    recordMetric: (name, value) => perfMonitor.recordMetric(`${componentName}-${name}`, value)
  };
}

/**
 * 资源优化建议
 */
export const optimizationTips = {
  // 检查是否有未使用的computed
  checkUnusedComputed() {
    if (isDev) {
      perfLogger.info('提示: 定期检查是否有未使用的computed属性');
    }
  },
  
  // 检查是否有过度的deep watch
  checkDeepWatchers() {
    if (isDev) {
      perfLogger.info('提示: 避免过多的deep watch，考虑使用shallow watch');
    }
  },
  
  // 检查组件是否过大
  checkComponentSize(componentName, lineCount) {
    if (isDev && lineCount > 500) {
      perfLogger.warn(`组件较大: ${componentName} (${lineCount}行)，建议拆分`);
    }
  }
};

// 开发环境下定期生成性能报告
if (isDev) {
  setInterval(() => {
    perfMonitor.generateReport();
  }, 60000); // 每分钟生成一次报告
}